package org.lanqiao.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class CORSFilter
 */
@WebFilter(description = "解决跨域请求，cors", urlPatterns = { "/*" })
public class CORSFilter implements Filter {

    /**
     * Default constructor. 
     */
    public CORSFilter() {
        
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		HttpServletResponse res = (HttpServletResponse)response;
		HttpServletRequest req=(HttpServletRequest)request;
		//System.out.println(req.getHeader("Origin")+",Corsfilter  ");//获得请求的源
		/**
		 * 当跨域携带凭证的时候，需要设置源为固定的，"*" 设置为req.getHeader("Origin")；；但是只能解决post请求
		 */
		res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
		res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		res.setHeader("Access-Control-Max-Age", "3600");//预期检查的缓存时间，因为ajax请求会，请求两次，第一次会验证，使用上    OPTIONS协议
		res.setHeader("Access-Control-Allow-Headers", "x-requested-with"); 
		res.setHeader("Access-Control-Allow-Credentials", "true");//设置允许携带凭证
		
		chain.doFilter(request, res);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
